package thread.java20230112;

import java.util.concurrent.CountDownLatch;

public class Demo53 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);
        Runnable runnable = ()->{
            try {
                String name = Thread.currentThread().getName();
                //模拟运动员跑步, 随机休眠几秒
                //Math.random()  [0,1)
                Thread.sleep((long) (Math.random() * 1000 + 3000));//休眠3-4秒
                //跑到终点
                System.out.println(name + "跑到终点");
                latch.countDown();//计数器-1
            }catch (Exception e){
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread(runnable, "运动员" + i).start();
        }
        //等待所有线程执行完成
        latch.await();//在线程未全部执行完成时, 会一直阻塞
        //当latch = 0时, 执行后续操作
        System.out.println("比赛结束");
    }
}
